import asyncio


class AsyncResourceManager:
    """异步资源管理"""

    def __init__(self, max_concurrent=3):
        self.semaphore = asyncio.Semaphore(max_concurrent)
        self.lock = asyncio.Lock()
        self.shared_resource = 0

    async def access_limited_resource(self, name):
        """访问受限制的资源"""
        async with self.semaphore:
            print(f"{name} 获得资源访问权")
            await asyncio.sleep(1)  # 模拟资源使用
            print(f"{name} 释放资源访问权")

    async def update_shared_resource(self, name, value):
        """更新共享资源（需要锁）"""
        async with self.lock:
            print(f"{name} 获得锁，当前资源值: {self.shared_resource}")
            await asyncio.sleep(0.5)  # 模拟处理时间
            self.shared_resource += value
            print(f"{name} 更新资源为: {self.shared_resource}")
            print(f"{name} 释放锁")


async def concurrency_control():
    """并发控制演示"""
    manager = AsyncResourceManager(max_concurrent=2)

    # 测试信号量
    print("=== 信号量测试 ===")
    semaphore_tasks = [manager.access_limited_resource(f"任务{i}") for i in range(5)]
    await asyncio.gather(*semaphore_tasks)

    # 测试锁
    print("\n=== 锁测试 ===")
    lock_tasks = [manager.update_shared_resource(f"更新者{i}", i + 1) for i in range(3)]
    await asyncio.gather(*lock_tasks)


asyncio.run(concurrency_control())
